package com.schoolcloud.gateway.config;

import cn.dev33.satoken.stp.StpInterface;
import com.schoolcloud.api.client.front.FrontPermissionClient;
import com.schoolcloud.api.client.front.FrontRoleClient;
import com.schoolcloud.common.model.R;
import com.schoolcloud.api.client.front.FrontUserClient;
import com.schoolcloud.api.client.SystemClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
@Slf4j
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    /**
     * 远程调用
     */
    private final SystemClient systemClient;

    private final FrontPermissionClient frontClient;
    private final FrontRoleClient frontRoleClient;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        CompletableFuture<R<List<String>>> r;
        if (loginType.equals(FroUserStpUtil.TYPE)) {
            r = CompletableFuture.supplyAsync(() -> {
//            远程调用，发送feign请求获取用户权限
                return frontClient.getPermissionCodesByUserId(String.valueOf(loginId));
            });
        } else {
            r = CompletableFuture.supplyAsync(() -> {
//            远程调用，发送feign请求获取用户权限
                return systemClient.getUserPermissionCode(String.valueOf(loginId));
            });
        }
        try {
            return r.get().getData();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        CompletableFuture<R<List<String>>> r;
        if (loginType.equals(FroUserStpUtil.TYPE)) {
            r = CompletableFuture.supplyAsync(() -> frontRoleClient.getFroRoleCodesByUserId(String.valueOf(loginId)));
        } else {
            r = CompletableFuture.supplyAsync(() -> systemClient.getUserRoleCode(String.valueOf(loginId)));
        }
        try {
            return r.get().getData();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
